﻿using System;

namespace GiteeApi.Utils
{
    /// <summary>
    /// 随机验证码
    /// </summary>
    public class RandomCode
    {
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="codeLen">数据的长度</param>
        /// <returns></returns>
        public static string Create(int codeLen = 4)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] allCharAry = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeLen; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int) DateTime.Now.Ticks));
                }

                int t = rand.Next(35);
                if (temp == t)
                {
                    return Create(codeLen);
                }

                temp = t;
                randomCode += allCharAry[t];
            }

            return randomCode;
        }
    }
}